package com.limf.demo.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;


public class CommonUtil {

	
	/**
	 * 根据名称取common.properties文件里面配置的值
	 * @param name
	 * @return
	 * @throws IOException
	 */
	public static String getCommonValue(String name) throws IOException {
		
		if (name==null || name.trim().length() <= 0) {
			return "";
		}
		InputStream in = CommonUtil.class.getClassLoader().getResourceAsStream("config.properties");
		Properties p = new Properties();
		p.load(in);
		String value = p.getProperty(name);
		return value;
	}
	
	/**
	 * 生成javabean的外部框代码内容
	 * @param fileName
	 * @return
	 */
	public static String convertJB_struct(String fileName) {
		StringBuilder sb_str = new StringBuilder();
		fileName = StringUtils.capitalize(convertString(fileName));
		sb_str.append("\rpublic class "+fileName +"{}");
		
		System.out.println("\rpublic class "+fileName +"{}");
		return sb_str.toString();
	}
	
	/**
	 * 转换字符串，数据字段与对象属性的转换
	 */
	public static String convertData(String fileName, String filePath) {
		
		
		StringBuilder sbn = new StringBuilder();
		StringBuilder sbn_struct = new StringBuilder();
		StringBuilder sbn_jb = new StringBuilder();
		StringBuilder sbn_struct_p1 = new StringBuilder();
		StringBuilder sbn_struct_p2 = new StringBuilder();
		
		
		try {
			List<String> lines = FileUtils.readLines(new File(filePath),"utf-8");
			System.out.println(lines.size()+"个");
			
			sbn_struct.append("\npublic "+StringUtils.capitalize(convertString(fileName))+"(){super();}\n");
			
			for (String s : lines) {  
				
	            if(StringUtils.isBlank(s))
	            	continue;
	            s = s.trim();
	            //System.out.println(s);
	            //System.out.println(s);
	            String[] cols = s.split(" ");
	            if(cols[1].toUpperCase().contains("INT") || cols[1].toUpperCase().contains("NUMBER")) {
	            	
	            	String attrName = convertString(cols[0]);
	            	System.out.println("private Integer "+attrName+";");
	            	sbn.append("private Integer "+attrName+";\n");
	            	
	            	sbn_jb.append("public void "+convertString("set_"+cols[0])+"(int "+attrName+"){this."+attrName+"="+attrName+";}\n");
	            	sbn_jb.append("public int "+convertString("get_"+cols[0])+"(){return this."+attrName+";}\n");
	            	System.out.println("public void "+convertString("set_"+cols[0])+"(int "+attrName+"){this."+attrName+"="+attrName+";}");
	            	System.out.println("public int "+convertString("get_"+cols[0])+"(){return this."+attrName+";}");
	            	
	            	sbn_struct_p1.append("int "+attrName+", ");
	            	sbn_struct_p2.append("this."+attrName+" = "+attrName+";\n");
	            }else if(cols[1].toUpperCase().contains("VARCHAR") || cols[1].toUpperCase().contains("TEXT"))
	            {
	            	String attrName = convertString(cols[0]);
	            	System.out.println("private String "+attrName+";");
	            	sbn.append("private String "+attrName+";\n");
	            	
	            	sbn_jb.append("public void "+convertString("set_"+cols[0])+"(String "+attrName+"){this."+attrName+"="+attrName+";}\n");
	            	sbn_jb.append("public String "+convertString("get_"+cols[0])+"(){return this."+attrName+";}\n");
	            	System.out.println("public void "+convertString("set_"+cols[0])+"(String "+attrName+"){this."+attrName+"="+attrName+";}");
	            	System.out.println("public String "+convertString("get_"+cols[0])+"(){return this."+attrName+";}");
	            	
	            	sbn_struct_p1.append("String "+attrName+", ");
	            	sbn_struct_p2.append("this."+attrName+" = "+attrName+";\n");
	            }else if(cols[1].toUpperCase().contains("TIMESTAMP")) {
	            	String attrName = convertString(cols[0]);
	            	System.out.println("private Date "+attrName+";");
	            	sbn.append("private Date "+attrName+";\n");
	            	
	            	sbn_jb.append("public void "+convertString("set_"+cols[0])+"(Date "+attrName+"){this."+attrName+"="+attrName+";}\n");
	            	sbn_jb.append("public Date "+convertString("get_"+cols[0])+"(){return this."+attrName+";}\n");
	            	System.out.println("public void "+convertString("set_"+cols[0])+"(Date "+attrName+"){this."+attrName+"="+attrName+";}");
	            	System.out.println("public Date "+convertString("get_"+cols[0])+"(){return this."+attrName+";}");
	            	
	            	sbn_struct_p1.append("Date "+attrName+", ");
	            	sbn_struct_p2.append("this."+attrName+" = "+attrName+";\n");
	            }
	        }
			sbn_struct.append("\npublic "+StringUtils.capitalize(convertString(fileName))+"("+sbn_struct_p1.substring(0, sbn_struct_p1.length()-2)+"){\n"+sbn_struct_p2.toString()+"\n}\n");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sbn.append("\n").append(sbn_struct.toString()).append(sbn_jb).toString();
	}
	
	public static String convertString(String value) {
		String[] vals = value.split("_");
		StringBuffer retVal = new StringBuffer();
		for (int i=0;i<vals.length;i++) {
			String val = vals[i].toLowerCase();
			if(i==0)
				retVal.append(val);
			else 
				retVal.append(StringUtils.capitalize(val));
		}
		
		return retVal.toString();
	}
	
	public static String convertString2(String value) {
		String[] vals = value.split("_");
		StringBuffer retVal = new StringBuffer();
		for (int i=0;i<vals.length;i++) {
			String val = vals[i].toLowerCase();
			retVal.append(StringUtils.capitalize(val));
		}
		
		return retVal.toString();
	}
	
	public static void convertInsertSql(String tableName, String filePath) {
		try {
			StringBuffer sql = new StringBuffer("insert into "+tableName+"(");
			List<String> lines = FileUtils.readLines(new File(filePath),"utf-8");
			int lineNum = lines.size();
			System.out.println(lines.size()+"个");
			for (String s : lines) {  
	            if(StringUtils.isBlank(s))
	            {
	            	lineNum--;
	            	continue;
	            }
	            s = s.trim();
	            
	            String[] cols = s.split(" ");
	            sql.append(cols[0]).append(", ");
	        }
			sql = new StringBuffer(sql.substring(0, sql.length()-2)).append(") values(");
			sql.append(StringUtils.repeat("?, ", lines.size()-1)).append("?)");
			System.out.println(sql);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
	
	public static void convertUpdateSql(String tableName, String filePath) {
		try {
			StringBuffer sql = new StringBuffer("update "+tableName + " set ");
			List<String> lines = FileUtils.readLines(new File(filePath),"utf-8");
			int lineNum = lines.size();
			System.out.println(lines.size()+"个");
			for (String s : lines) {  
	            if(StringUtils.isBlank(s))
	            {
	            	lineNum--;
	            	continue;
	            }
	            s = s.trim();
	            
	            String[] cols = s.split(" ");
	            sql.append(cols[0]).append("=?, ");
	        }
			sql = new StringBuffer(sql.substring(0, sql.length()-2)).append("  where ");
			System.out.println(sql);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
	
	
	public static void convertSelectSql(String tableName, String filePath) {
		try {
			StringBuffer sql = new StringBuffer("select ");
			List<String> lines = FileUtils.readLines(new File(filePath),"utf-8");
			int lineNum = lines.size();
			System.out.println(lines.size()+"个");
			for (String s : lines) {  
	            if(StringUtils.isBlank(s))
	            {
	            	lineNum--;
	            	continue;
	            }
	            s = s.trim();
	            
	            String[] cols = s.split(" ");
	            sql.append(cols[0]).append(", ");
	        }
			sql = new StringBuffer(sql.substring(0, sql.length()-2)).append(" from ").append(tableName);
			System.out.println(sql);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
	
	public static void convertSetData(String filePath) {
		try {
			
			List<String> lines = FileUtils.readLines(new File(filePath),"utf-8");
			System.out.println(lines.size()+"个");
			for (String s : lines) {  
	            if(StringUtils.isBlank(s))
	            	continue;
	            s = s.trim();
	            //System.out.println(s);
	            //System.out.println(s);
	            String[] cols = s.split(" ");
	            if(cols[1].toUpperCase().contains("INT") || cols[1].toUpperCase().contains("NUMBER")) {
	            	System.out.println("test.set"+convertString2(cols[0])+"(rs.getInt(\""+cols[0]+"\"));");
	            }else if(cols[1].toUpperCase().contains("VARCHAR") || cols[1].toUpperCase().contains("TEXT"))
	            {
	            	System.out.println("test.set"+convertString2(cols[0])+"(rs.getString(\""+cols[0]+"\"));");
	            }else if(cols[1].toUpperCase().contains("TIMESTAMP")) {
	            	System.out.println("test.set"+convertString2(cols[0])+"(rs.getDate(\""+cols[0]+"\"));");
	            }
	        } 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
	
	/**
	 * 根据分区租金获取等级
	 * @param zjPrice
	 * @return
	 */
	public static String queryGradeValueByZj(BigDecimal zjPrice) {
		if(zjPrice == null)
			return "";
		if (zjPrice.intValue()<40)
			return "第四等级";
		else if(zjPrice.intValue()>=40 && zjPrice.intValue()<60)
			return "第三等级";
		else if(zjPrice.intValue()>=60 && zjPrice.intValue()<80)
			return "第二等级";
		else if(zjPrice.intValue()>=80)
			return "第一等级";
		return "";
	}
	
	/**
	 * 根据行政区获取行政区小写字母
	 * @param regionNo
	 * @return
	 */
	public static String queryLowerCaseRegion(String region) {
		
		if(region==null)
			return "";
		else if(region.trim().equals("福田区"))
			return "FT";
		else if(region.trim().equals("罗湖区"))
			return "LH";
		else if(region.trim().equals("南山区"))
			return "NS";
		else if(region.trim().equals("宝安区"))
			return "BA";
		else if(region.trim().equals("龙岗区"))
			return "LG";
		else if(region.trim().equals("盐田区"))
			return "YT";
		return "";
	}
	
	/**
	 * 根据数字取日期
	 * @param caseNum 0-所有；1-半年；2-1年
	 * @return
	 */
	public static String queryTimeByNum(int caseNum) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		if(caseNum == 1)
		{
			calendar.add(Calendar.MONTH, -6);
			return sdf.format(calendar.getTime());
		}else if(caseNum == 2) {
			calendar.add(Calendar.YEAR, -1);
			return sdf.format(calendar.getTime());
		}
		return "";
	}
	
	public static void main(String[] args) {
		
		/**
		 * 转换添加sql语句
		 
		convertInsertSql("share_resource", "D:/项目资料/java/data.txt"); 
		 */
		
		/**
		 * 转换修改sql语句
		 
		convertUpdateSql("share_resource", "D:/项目资料/java/data.txt");
		 */
		
		/**
		 * 转换查询sql语句
		 
		convertSelectSql("share_resource", "D:/项目资料/java/data.txt");   // E:/你妹/java/第三方类库/convertSql_select.txt
		*/
		
		/*
		 * 转换数据库字段
		 * */
		String test = "D:/项目资料/java/data.txt";
		convertData("travel_internal_result", test);
		
		
		/**
		 * 转换赋值setObj
		 
		convertSetData("D:/项目资料/java/data.txt"); 
		*/
		// 生成javaBean
		//generateJavaBean("share_resource", "D:/项目资料/java/data.txt");
	}
	
	public static void generateJavaBean(String fileName, String dataFile) {

		// 创建临时文件夹
		int index1 = dataFile.lastIndexOf("/");
		String folder = dataFile.substring(0, index1)+"/tmp";
		File file1_fd = new File(folder);
		if(!file1_fd.exists()) {
			file1_fd.mkdir();
		}
		
		// 创建文件
		String jb1 = folder + "/" + StringUtils.capitalize(convertString(fileName)) + ".java";
		File jb1_file = new File(jb1);
		if(jb1_file.exists()) {
			jb1_file.delete();
		}
		try {
			jb1_file.createNewFile();
		
			// 写文件数据
			String data_struct = convertJB_struct(fileName);
			String dataDefine = convertData(fileName, dataFile);
	        FileWriter fileWritter = new FileWriter(jb1, true);
	        fileWritter.write(data_struct.substring(0, data_struct.lastIndexOf("}")));
	        fileWritter.write(dataDefine);
	        fileWritter.write("}");
	        
	        fileWritter.close();
	        
	        
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
